package org.ljy.forum6.services.impl;


import lombok.extern.slf4j.Slf4j;
import org.ljy.forum6.common.AppResult;
import org.ljy.forum6.common.ResultCode;
import org.ljy.forum6.dao.ArticleMapper;
import org.ljy.forum6.exception.ApplicationException;
import org.ljy.forum6.model.Article;
import org.ljy.forum6.model.User;
import org.ljy.forum6.services.IArticleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文章
 */


@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private UserServiceImpl userService;

    @Resource
    private BoardServiceImpl boardService;

    /**
     * 发布新文章
     * @param article
     */
    @Override
    public void create(Article article) {
        //1.参数验证
        if(article==null
        || article.getTitle()==null || article.getContent()==null
        || article.getContent().trim().length()==0
        || article.getUserId()<=0 || article.getBoardId()<=0 ){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.设置文章默认值
        article.setLikeCount(0);
        article.setReplyCount(0);
        article.setVisitCount(0);
        article.setState((byte) 0);
        article.setDeleteState((byte) 0);
        Date now = new Date();
        article.setCreateTime(now);
        article.setUpdateTime(now);
        //3.调用dao
        Integer row = articleMapper.insert(article);
        if(row != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //4.更新作者的文章数和版块文章数
        userService.addOneArticleCountById(article.getUserId());
        boardService.addOneArticleCountById(article.getBoardId());
    }

    /**
     * 获取所有的文章
     * @return
     */
    @Override
    public List<Article> selectAll() {
        List<Article> articles = articleMapper.selectAll();
        return articles;
    }

    /**
     * 查询指定版块下的所有文章
     * @return
     */
    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        //1.参数验证
        if(boardId == null || boardId<=0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.调用dao
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);

        return articles;
    }

    /**
     * 获取指定帖子详情
     * @return
     */
    @Override
    public Article selectDetailById(Long id) {
        //1.参数校验
        if(id==null || id<=0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.调用dao
        Article article = articleMapper.selectDetailById(id);
        if(article == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setVisitCount(article.getVisitCount()+1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        article.setVisitCount(article.getVisitCount()+1);
        return article;
    }

    /**
     * 查询指定id文章
     * @return
     */
    @Override
    public Article selectById(Long id) {
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    /**
     * 编辑帖子（更新帖子）
     * @param id 文章id
     * @param title 文章标题
     * @param content 文章内容
     */
    @Override
    public void modify(Long id, String title, String content) {
        //1.参数校验


        //2.查询文章是否存在
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null || article.getDeleteState()==1 ) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //3.新建文章对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());
        //4.调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        log.info("更新成功");
    }
    /**
     * 点赞操作
     * @param id 文章id
     */
    @Override
    public void thumbsUpById(Long id) {

        //1.参数校验
        //2.获取对应文章对象
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null || article.getDeleteState()==1 ) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //3.构造新对象进行更新点赞数
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setLikeCount(article.getLikeCount()+1);
        //4.调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        log.info("新增点赞成功");
    }

    /**
     * 删除帖子
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        //1.参数校验
        if(id==null || id<=0) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //2.查询文章
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null || article.getDeleteState()==1 ) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //3.对文章进行逻辑删除
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setDeleteState((byte) 1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if( row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //4.对应位置-1
        boardService.subOneArticleCountById(article.getBoardId());
        userService.addOneArticleCountById(article.getUserId());

        log.info("删除帖子成功");
    }

    /**
     * 文章回复数+1
     */
    @Override
    public void addOneReplyCountById(Long id) {
        //1.参数校验
        if(id==null || id<=0) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //2.获取文章
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null || article.getDeleteState()==1 ) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //3.构建更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setReplyCount(article.getReplyCount()+1);
        //4.调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
    }

    /**
     *
     * @param userId
     * @return
     */
    @Override
    public List<Article> selectByUserId(Long userId) {
        //1.参数校验
        if(userId==null || userId<=0) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User user = userService.selectById(userId);
        if(user==null || user.getDeleteState()==1 ) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.
        List<Article> articles = articleMapper.selectByUserId(userId);
        if(articles==null) {
            articles = new ArrayList<Article>();
        }
        return articles;
    }

}
